﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using System.Security.Claims;
using DataMonitor_Tools.Tools;

using DataMonitorWebApi.Modals;
using DataMonitor_IBLL;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DataMonitorWebApi.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly string controllerName;
        private readonly IBLL_Login _ibLL_login;
        public LoginController(ILogger<LoginController> logger, IBLL_Login ibLL_login)
        {
            _logger = logger;
            _ibLL_login = ibLL_login;
            controllerName = this.GetType().Name;
        }
        [HttpPost]
        //post请求[FromBody]标记参数为对象需要使用json的格式进行传递，然后postman在"Body"框下选择"raw"，参数类型不要写错
        public IActionResult Login([FromBody] LoginModel user)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var md5key = MD5Encode.GetMD5Encode(user.password, "utf-8");
            var u = _ibLL_login.LoadEntities(a => a.loginname == user.loginname && a.password == md5key).FirstOrDefault();
            if (u != null)
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");
                var claims = new List<Claim>
           {
            new Claim(ClaimTypes.Name, user.loginname),
            new Claim(ClaimTypes.Role,u.authoritykey==1?"user":"admin")
           };
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
                u.password = null;
                return Ok(u);
                //return Ok(u.authoritykey == 1 ? "user" : "admin");
            }
            else
            {
                //await Task.CompletedTask;
                return BadRequest("用户名或密码错误");
            }
        }
        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            await base.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");
            return Ok("成功退出");
        }
        [HttpGet]
        public IActionResult NoAuthResult()
        {
            _logger.LogInformation("没有权限");
            return BadRequest("没有权限");
        }
    }
}
